﻿using System.Text;

namespace TPXSDK.NET.Mission.Instruction;

internal class InstHover : Tokenizer

{
    public InstHover(TokenizerAdmin admin)
    {
        Admin = admin;
        KeyName = "hover";
        KeyValue = (byte)FlyCmdId.CMD_HOVER;
        Usage = "hover [(hoverpoint)] [,alt]";
        Description = @"hover at specail location";
    }

    /// <inheritdoc />
    /// <summary>
    /// 词元分析器处理过程
    /// </summary>
    public override bool Process()
    {
        var flyCmp = Admin?.Compiler; 
        var tokens = flyCmp?.GetLineTokens();
        // 无效参数过滤
        if (null == tokens || tokens.Count > 3)
        {
            if(null != flyCmp) flyCmp.ErrorMsg = "Invalid Usage";
            return false;
        }

        var result = false;
        var cmd = new FlyCmdItem
        {
            Id = (byte)KeyValue,
            LineNum = tokens[0].Row
        };

        if (1 == tokens.Count)
        {
            cmd.P1 = (byte)ParaType.EMPTY;
            cmd.P2 = 0;
            result = true;
        }
        else
        {
            tokens.RemoveAt(0);// Remove Flycmd Name
            if (tokens[0].Type == TokenType.ABS_POS || tokens[0].Type == TokenType.REL_POS)
            {
                result = FlyUtils.WpToken2CmdItemP1(tokens[0], cmd);
                if (result && tokens.Count == 2 && tokens[1].Type == TokenType.NUMBER)
                {
                    cmd.P2 = Convert.ToInt16(tokens[1].Name);
                }
            }
            else
            {
                if (tokens.Count == 1 && tokens[0].Type == TokenType.NUMBER)
                {
                    cmd.P1 = (byte)ParaType.NUMBER;
                    cmd.P2 = Convert.ToInt16(tokens[0].Name);
                    result = true;
                }
            }
        }

        if (result)
        {
            flyCmp?.CmdList.Add(cmd);
        }

        return result;
    }

    public override void Reverse(FlyCmdItem cmd, StringBuilder sb)
    {
        var src = $"{KeyName} {FlyUtils.ParseWpFromCmdItem(cmd)}";
        if (cmd.P1 == (byte)ParaType.EMPTY)
        {
            src = $"{KeyName}";
        }
        else if (cmd.P1 == (byte)ParaType.NUMBER)
        {
            src = $"{KeyName} {cmd.P2}//m";
        }
        else
        {
            if (cmd.P2 != 0)
                src = $"{KeyName} {FlyUtils.ParseWpFromCmdItem(cmd)}, {cmd.P2}";
        }

        sb.AppendLine(src);
    }
}
